package com.qf.service.impl;

import com.qf.entity.User;
import com.qf.mapper.UserMapper;
import com.qf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Random;

//用户业务逻辑层
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String from;
    @Autowired
    TemplateEngine templateEngine;
    @Autowired
    private UserMapper userMapper;
    /**
     * 获取验证码
     * @param u_phone
     * @param request
     * @return
     */
    @Override
    public String getCode(String u_phone, HttpServletRequest request) {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(from);
            mimeMessageHelper.setTo(u_phone);
            mimeMessageHelper.setSubject("电竞验证码");
            //生成随机数
            String random = randomInteger();
            //将随机数放置到session中
            HttpSession session = request.getSession();
            session.setAttribute(u_phone,random);
            mimeMessageHelper.setText("<font style='color:red'>"+random+"</font>",true);

            javaMailSender.send(mimeMessage);
            return random;

        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 注册
     * @param user
     * @return
     */
    @Override
    public int register(User user) {
        return userMapper.register(user);
    }

    /**
     * 登录
     * @param user
     * @return
     */
    @Override
    public User userLogin(User user) {
        String u_name = user.getU_name();
        String u_pwd = user.getU_pwd();
        System.out.println("=====SSSSSSSSSSSSSSSSSSSSSSS==========="+user);
        return userMapper.userLogin(u_name,u_pwd);
    }

    /**
     * 生成随机数
     * @return
     */
    public String randomInteger() {
        Random random = new Random();
        StringBuffer stringBuffer = new StringBuffer();
        //生成6位的随机数
        for (int i = 0;i<6;i++){
            int i1 = random.nextInt(10);
            stringBuffer.append(i1);
        }
        return stringBuffer.toString();

    }
}
